package models

import (
	"time"

	. "gddgame.cc/galaxy/common/dsl/db"
	"gddgame.cc/galaxy/common/thirdparty/facebook"
	"gddgame.cc/galaxy/common/thirdparty/google"
	"gddgame.cc/galaxy/common/thirdparty/mi"
	"gddgame.cc/galaxy/common/thirdparty/qq"
	"gddgame.cc/galaxy/common/thirdparty/wechat"
	"gddgame.cc/galaxy/utils/orm"

	"github.com/speps/go-hashids"
)

var (
	AppModel = orm.NewModel("app", &App{
		Name:      "",
		Icon:      "",
		AppId:     "",
		AppToken:  "",
		AppKey:    "",
		AppSecret: "",
	}, nil)
)

func init() {
	AddTable(&Table{
		Model: AppModel,
	})
}

type App struct {
	Id   int    `json:"id" orm:"auto" sql:"INT"`
	Name string `json:"name" sql:"VARCHAR"`
	Icon string `json:"icon" sql:"VARCHAR"`

	// 用来客户端链接服务器
	AppId string `json:"app_id" sql:"VARCHAR"`
	// 用来客户端链接服务器, 可以按版本进行区分
	AppToken string `json:"app_token" sql:"VARCHAR"`
	// 用来进行跨服务的秘要，内部使用
	JwtSecret string `json:"jwt_secret" sql:"VARCHAR"`

	// 用来做app服务端访问平台接口的key，联合secret使用
	AppKey string `json:"app_key" sql:"VARCHAR"`
	// 用来做签名处理，验证输入是否有效
	AppSecret string `json:"app_secret" sql:"VARCHAR"`

	// {app_id:, bundle_id:}
	Ios string `json:"ios" sql:"TEXT"`
	// {bundle_id:}
	Android string `json:"android" sql:"TEXT"`
	// {}
	Windows string `json:"windows" sql:"TEXT"`

	WechatAppId     string `json:"wechat_app_id" sql:"VARCHAR"`
	WechatAppSecret string `json:"wechat_app_secret" sql:"VARCHAR"`

	FacebookAppId     string `json:"facebook_app_id" sql:"VARCHAR"`
	FacebookAppSecret string `json:"facebook_app_secret" sql:"VARCHAR"`

	QQAppId     string `json:"qq_app_id" sql:"VARCHAR"`
	QQAppSecret string `json:"qq_app_secret" sql:"VARCHAR"`

	GoogleAppId     string `json:"google_app_id" sql:"VARCHAR"`
	GoogleAppSecret string `json:"google_app_secret" sql:"VARCHAR"`

	MiAppId     string `json:"mi_app_id" sql:"VARCHAR"`
	MiAppSecret string `json:"mi_app_secret" sql:"VARCHAR"`

	CreateTime *time.Time `json:"create_time" orm:"createTime" sql:"DATETIME"`
	UpdateTime *time.Time `json:"update_time" orm:"updateTime" sql:"DATETIME"`
	DeleteTime *time.Time `json:"delete_time" orm:"deleteTime" sql:"DATETIME"`

	hashIds  *hashids.HashID
	Wechat   *wechat.Client   `json:"-"`
	Facebook *facebook.Client `json:"-"`
	QQ       *qq.Client       `json:"-"`
	Google   *google.Client   `json:"-"`
	Mi       *mi.Client       `json:"-"`
}

func (app *App) initHash() {
	if app.hashIds == nil {
		app.hashIds, _ = hashids.NewWithData(&hashids.HashIDData{Alphabet: hashids.DefaultAlphabet, MinLength: 6, Salt: app.AppKey})
	}
}

func (app *App) EncodeUser(userId int) string {
	app.initHash()
	id, _ := app.hashIds.Encode([]int{app.Id, userId})
	return id
}

func (app *App) DecodeUser(openId string) int {
	app.initHash()
	ids, _ := app.hashIds.DecodeWithError(openId)
	return ids[1]
}
